package com.ncbee.base.config.common;


import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.ncbee.base.config.common.converter.DateConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Author fengzirong
 * @DESC
 * @Date 2018/11/29 15:22
 **/
@Configuration
public class CustomWebConfig implements WebMvcConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(CustomWebConfig.class);

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers){

        logger.info("------baseQuery参数解析器开始加入解析器列表------");
        resolvers.add(new CustomDatabind());
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        logger.info("------日期转换器开始加入转换器列表------");
        registry.addConverter(new DateConverter());
    }

    /**
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.forEach(e -> {
            if (e instanceof MappingJackson2HttpMessageConverter) {
                MappingJackson2HttpMessageConverter converter = (MappingJackson2HttpMessageConverter) e;
                SimpleModule simpleModule = new SimpleModule();
                simpleModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                simpleModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                simpleModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
                simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
                converter.getObjectMapper().registerModule(simpleModule);
            }
        });
    }

}
